/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-08-18     SY       the first version
 */
#include "rtthread.h"
#include "sy_flash.h"
#include <stddef.h>
#include "sy_fs.h"


disk_t disk=
{
        .base_addr=(unsigned int*)0x08004000,
        .disk_size=2048,
        .name="disk1",
        .start_addr=(unsigned int*)0x08004000
};

fat_t system_fat;

Fat fs_write_table(Disk disk);
Fat fs_read_table(Disk disk);

Fat fs_init()
{

    if(fs_read_table(&disk)!=NULL)
    {
        return &system_fat;
    }
    fs_write_table(&disk);
    fs_read_table(&disk);
		
		return NULL;
}

Fat fs_write_table(Disk disk)
{
    Fat fat=NULL;
    if(disk==NULL)
    {
        return NULL;
    }
    fat=(Fat)rt_malloc(sizeof(fat_t));
    rt_memset(fat,0,sizeof(fat_t));
    if(fat==NULL)
    {
        return NULL;
    }
    rt_memset(&fat->file, 0,sizeof(file_t));
    rt_memset(&fat->disk,0,sizeof(disk_t));
    rt_memcpy(&fat->disk,disk,sizeof(disk_t));
    fat->file_size=0;
    fat->offset=2048U;
    fmc_erase_pages((unsigned int)disk->base_addr,2048);
    fmc_program((unsigned int)disk->base_addr,fat,sizeof(fat_t));
    rt_kprintf("fmc_program:0x%x\n",disk->base_addr);
    return fat;
}
Fat fs_read_table(Disk disk)
{
    //rt_memcpy(&system_fat,(uint32_t*)disk->base_addr,sizeof(fat_t));
    rt_memcpy(&system_fat,disk->base_addr,sizeof(fat_t));
    rt_kprintf("disk_name:%s file_size:%d offset:0x%x\n",system_fat.disk.name,system_fat.file_size,system_fat.offset);
    if(system_fat.file_size==0xffffffff||system_fat.offset==0xffffffff)
    {
        rt_kprintf("fat read error\n");
        return NULL;
    }
    else if(rt_strcmp(disk->name, system_fat.disk.name)!=0)
    {
        rt_kprintf("fat read error\n");
        return NULL;
    }
    return &system_fat;
}
File fs_open(char *name,char *flag)
{

    for(int i=0;i<system_fat.file_size;i++)
    {
				if(rt_strcmp(name,system_fat.file.name)==0)
				{
					break;
				}
    }
		return NULL;
}

